﻿using AutoMapper;
using ERPSystem.Common.Domains.Material;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;

namespace BasicInformationCommon.API.BasicInformationCommons.Materiales
{
    public class MaterialesTreeQueryHandler : IRequestHandler<MaterialesTreeQueryCommand, Result>
    {
        private readonly IBaseRepository<MaterialCascade>  _materialCascadeRepository;

        public MaterialesTreeQueryHandler(IBaseRepository<MaterialCascade> materialCascadeRepository)
        {
            _materialCascadeRepository = materialCascadeRepository;
        }

        /// <summary>
        /// 物料分类树形
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(MaterialesTreeQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                var materialTree = await (await _materialCascadeRepository.GetAll()).Where(x => x.PId == 0).ToListAsync();
                List<Cascard> cascades = new List<Cascard>();

                foreach (var material in materialTree)
                {
                    Cascard cascade = new Cascard();
                    cascade.value = material.MaterialTypeId;
                    cascade.label = material.MaterialTypeName;
                    cascade.children = await GetCascards(material.MaterialTypeId);
                    cascades.Add(cascade);
                }
                result.Data = cascades;

            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }

        public async Task<List<Cascard>> GetCascards(int pid = 0)
        {
            var materialTree = await (await _materialCascadeRepository.GetAll()).Where(x => x.PId == pid).ToListAsync();
            List<Cascard> cascades = new List<Cascard>();

            foreach (var material in materialTree)
            {
                Cascard cascade = new Cascard();
                cascade.value = material.MaterialTypeId;
                cascade.label = material.MaterialTypeName;
                cascade.children = await GetCascards(material.MaterialTypeId);
                cascades.Add(cascade);
            }
            return cascades;
        }
    }

}
